<script setup lang="ts">
import { ref, onMounted, h } from 'vue';
import { Page } from '@vben/common-ui';
import { NDataTable, NButton, NModal, NForm, NFormItem, NInput, useMessage } from 'naive-ui';
import { getPermissionPolicies, addPermissionPolicies, deletePermissionPolicies, type PermissionPolicy } from '#/api/authserver/permission';

const columns = [
  { key: 'subject', title: '主体' },
  { key: 'object', title: '对象' },
  { key: 'action', title: '操作' },
  {
    key: 'actions',
    title: '操作',
    render(row: any) {
      return [
        h(NButton, { size: 'small', type: 'error', onClick: () => handleDelete(row) }, { default: () => '删除' }),
      ];
    },
  },
];

const data = ref<PermissionPolicy[]>([]);
const loading = ref(false);
const message = useMessage();

// 弹窗相关
const showModal = ref(false);
const modalTitle = ref('添加权限策略');
const formModel = ref<PermissionPolicy>({
  subject: '',
  object: '',
  action: ''
});
const formLoading = ref(false);

async function fetchData() {
  loading.value = true;
  try {
    const res = await getPermissionPolicies();
    // API返回的是二维数组格式，需要转换为对象数组
    if (Array.isArray(res)) {
      data.value = res.map((item: any) => {
        if (Array.isArray(item) && item.length >= 3) {
          return {
            subject: item[0] || '',
            object: item[1] || '',
            action: item[2] || ''
          };
        }
        return item;
      });
    } else {
      data.value = [];
    }
  } catch (error) {
    console.error('获取权限策略失败:', error);
    message.error('获取权限策略失败');
    data.value = [];
  } finally {
    loading.value = false;
  }
}

onMounted(fetchData);

function handleCreate() {
  modalTitle.value = '添加权限策略';
  formModel.value = {
    subject: '',
    object: '',
    action: ''
  };
  showModal.value = true;
}

async function handleDelete(row: PermissionPolicy) {
  if (confirm('确定要删除该权限策略吗？')) {
    try {
      await deletePermissionPolicies([row]);
      message.success('删除成功');
      fetchData();
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  }
}

async function handleModalOk() {
  formLoading.value = true;
  try {
    // 验证必填字段
    if (!formModel.value.subject || !formModel.value.object || !formModel.value.action) {
      message.error('请填写完整的权限策略信息');
      return;
    }

    await addPermissionPolicies([formModel.value]);
    message.success('添加成功');
    showModal.value = false;
    fetchData();
  } catch (error) {
    console.error('添加失败:', error);
    message.error('添加失败');
  } finally {
    formLoading.value = false;
  }
}
</script>

<template>
  <Page description="权限策略管理" title="权限策略管理">
    <div class="mb-4 flex justify-end">
      <NButton type="primary" @click="handleCreate">添加权限策略</NButton>
    </div>
    <NDataTable :columns="columns" :data="data" :loading="loading" />
    <NModal v-model:show="showModal" :title="modalTitle" preset="dialog" :loading="formLoading" :mask-closable="false" :style="{ width: '600px' }">
      <NForm :model="formModel" label-width="100">
        <NFormItem label="主体" path="subject">
          <NInput v-model:value="formModel.subject" placeholder="请输入主体" />
        </NFormItem>
        <NFormItem label="对象" path="object">
          <NInput v-model:value="formModel.object" placeholder="请输入对象" />
        </NFormItem>
        <NFormItem label="操作" path="action">
          <NInput v-model:value="formModel.action" placeholder="请输入操作" />
        </NFormItem>
      </NForm>
      <template #action>
        <NButton type="primary" :loading="formLoading" @click="handleModalOk">确定</NButton>
        <NButton class="ml-2" @click="() => (showModal = false)">取消</NButton>
      </template>
    </NModal>
  </Page>
</template>

<style scoped></style>
